from django.shortcuts import render

# Create your views here.
from django.contrib.auth.models import User, Group
from .models import TaskModel, TaskList, MyUser
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from nlspider.serializers import UserSerializer, GroupSerializer, TaskSerializer, TaskListSerializer, MyUserSerializer
import requests
from rest_framework.request import Request


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


class TaskViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = TaskModel.objects.all().order_by("-id")
    serializer_class = TaskSerializer


class TaskListViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = TaskList.objects.all()
    serializer_class = TaskListSerializer


class MyUserListViewSet(viewsets.ModelViewSet):
    """
    List all snippets, or create a new snippet.
    """
    queryset = MyUser.objects.all()
    serializer_class = MyUserSerializer


@api_view(['POST'])
def checkUser(request):
    """
    List all snippets, or create a new snippet.
    """
    if request.method == 'POST':
        data = request.data
        try:
            user = data['user']
            password = data['password']
            user = MyUser.objects.get(username=user)
            if user.password == password:
                return Response("success", status=status.HTTP_200_OK)
            else:
                return Response("password error", status=status.HTTP_400_BAD_REQUEST)
        except:
            return Response("invalid user", status=status.HTTP_401_UNAUTHORIZED)


def get_jobs():
    r = requests.get('http://127.0.0.1:6800/listjobs.json?project=nlproject')
    return r.json()


@api_view(['GET'])
def checkTask(request):  # TODO: 更新状态可以优化
    """
    List all snippets, or create a new snippet.
    """
    taskDict = get_jobs()
    pending = taskDict['pending']
    running = taskDict['running']
    finished = taskDict['finished']
    for i in pending:
        try:
            TaskList.objects.get(jid=i['id']).update(status='pending', startTime=i['start_time'], endTime=i['end_time'])
        except:
            pass
    for i in running:
        try:
            TaskList.objects.get(jid=i['id']).update(status='running', startTime=i['start_time'], endTime=i['end_time'])
            print(2222)
        except:
            pass
    for i in finished:
        try:
            TaskList.objects.filter(jid=i['id']).update(status='finished', startTime=i['start_time'], endTime=i['end_time'])
            print(33333)
        except:
            pass
    queryset = TaskList.objects.all()
    serializer = TaskListSerializer(queryset, many=True, context={'request': request})
    return Response(serializer.data)